#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/7 15:46
# @Author : 吴敬超
# explain:
from netCDF4 import Dataset, num2date

filename = "D:/NetCDFfile/ECMWF_mrt_20190101_v1.0_con.nc"

nc = Dataset(filename, 'r', Format='NETCDF4')
print nc.variables

print 'Variable List'

# for var in nc.variables:
#     print var, var.units, var.shape

# get coordinates variables
lats = nc.variables['lat'][:]
lons = nc.variables['lon'][:]
print '1111111111111111111111111111111111'

print  lats[3]
print lons[3]
print '1111111111111111111111111111111111'

sfc = nc.variables['mrt'][:]
times = nc.variables['time'][:]
#
# # convert date, how to store date only strip away time?
# print "Converting Dates"
# units = nc.variables['time'].units
# dates = num2date(times[:], units=units, calendar='365_day')
#
# # print [dates.strftime('%Y%m%d%H') for date in dates]
#
# header = ['Latitude', 'Longitude']
#
# # append dates to header string
#
# for d in dates:
#     print d
#     header.append(d)
#
# # write to file
# import csv
# # the csv file is closed when you leave the block
# with open('output.csv', 'wb') as csvFile:
#     outputwriter = csv.writer(csvFile, delimiter=',')
#     for time_index, time in enumerate(times): # pull the dates out for the header
#          t = num2date(time, units = units, calendar='365_day')
#          header.append(t)
#     outputwriter.writerow(header)
#     for lat_index, lat in enumerate(lats):
#         content = lat
#         print lat_index
#         for lon_index, lon in enumerate(lons):
#             content.append(lon)
#             print lon_index
#             for time_index, time in enumerate(times): # for a date
#                 # pull out the data
#                 data = sfc[time_index,lat_index,lon_index]
#                 content.append(data)
#                 outputwriter.writerow(content)
# # close the output file
# csvFile.close()
#
# # close netcdf
# nc.close()